#pragma once

#include "clipping.h"
#include "../extension/models.h"

namespace qbe::editing::Clipping {
void updateVisualRender(ecs::EventWriter<Clipping::Event> event_writer) {
  event_writer.send({Code::OpUpdate});
}
void clearVisualRender(ecs::EventWriter<Clipping::Event> event_writer) {
  event_writer.send({Code::OpExit});
}

void clearModeData(ecs::Query query) {
  auto& param = query.get_resource<ClippingModel>();
  param.clear();
  param.updateVisualData({}, {});  //更新可视化数据
  auto event_writer = query.get_event_writer<Clipping::Event>();
  clearVisualRender(event_writer);
}

void exit(ecs::Query query) {
  clearModeData(query);
  auto& state = query.get_resource<state::State>();
  state.switchMode(state::EditingModeType::None);
}

void exit_callback(ecs::Query query, state::AllModeType mode) {
  clearModeData(query);
}

//整体选择对象
std::vector<entt::entity> getSelectedObjs(entt::registry& reg) {
  std::vector<entt::entity> selected_objs;
  auto view = reg.view<select::SelectTag>();

  view.each([&selected_objs, &reg](entt::entity entity) {
    // 标记被移动的对象
    auto line = reg.try_get<qlib::Path::s_ptr>(entity);
    auto polygon = reg.try_get<qlib::Polygon::s_ptr>(entity);
    auto rectangle = reg.try_get<qlib::Rectangle::s_ptr>(entity);
    auto ellipse = reg.try_get<qlib::Ellipse::s_ptr>(entity);
    auto fan = reg.try_get<qlib::Fan::s_ptr>(entity);
    auto kp = reg.try_get<qlib::KeyPoint::s_ptr>(entity);
    if (line || polygon || rectangle || ellipse || fan || kp) {
      selected_objs.push_back(entity);
    }
  });

  return selected_objs;
}

void partSelectInfo2(entt::registry& cell_reg, entt::entity entity, select::SelectPartData data, std::vector<PartCheckedInfo>& part_selected_objs) {
  bool is_ellipse = false;
  auto _ptr_line = cell_reg.try_get<qlib::Path::s_ptr>(entity);
  auto _ptr_poly = cell_reg.try_get<qlib::Polygon::s_ptr>(entity);
  auto _ptr_elli = cell_reg.try_get<qlib::Ellipse::s_ptr>(entity);
  auto _ptr_rec = cell_reg.try_get<qlib::Rectangle::s_ptr>(entity);
  auto _ptr_fan = cell_reg.try_get<qlib::Fan::s_ptr>(entity);
  qlib::Vec2dArray points;
  if (_ptr_line)
    points = (*_ptr_line)->spine.points;
  if (_ptr_poly)
    points = (*_ptr_poly)->points;
  if (_ptr_elli) {
    qlib::Vec2dArray box = (*_ptr_elli)->bounding_box();
    points = qlib::box_to_points(box);
  }
  if (_ptr_rec)
    points = (*_ptr_rec)->to_polygon()->points;
  if (_ptr_fan)
    points = (*_ptr_fan)->to_polygon()->points;

  for (const auto& [edge_id, value] : data.edge_id_map) {
    PartCheckedInfo info;
    info.node = entity;
    info.key_points = points;
    info.is_ellipse = is_ellipse;
    info.indexs.push_back(edge_id);
    if ((edge_id + 1) == points.size()) {
      info.indexs.push_back(0);
    } else {
      info.indexs.push_back(edge_id + 1);
    }
    part_selected_objs.push_back(info);
  }
}

PartCheckedInfo partSelectInfo(entt::registry& cell_reg, select::SelectPartModel::Data select) {
  PartCheckedInfo result;
  result.node = select.entity;
  if (select.type == select::SelectPartType::Point) {
    auto _ptr_poly = cell_reg.try_get<qlib::Polygon::s_ptr>(select.entity);
    auto _ptr_elli = cell_reg.try_get<qlib::Ellipse::s_ptr>(select.entity);
    auto _ptr_rec = cell_reg.try_get<qlib::Rectangle::s_ptr>(select.entity);
    auto _ptr_fan = cell_reg.try_get<qlib::Fan::s_ptr>(select.entity);
    if (_ptr_poly || _ptr_elli || _ptr_rec || _ptr_fan) {
      qlib::Vec2dArray points;
      if (_ptr_poly)
        points = (*_ptr_poly)->points;
      if (_ptr_elli)
        points = (*_ptr_elli)->to_polygon()->points;
      if (_ptr_rec)
        points = (*_ptr_rec)->to_polygon()->points;
      if (_ptr_fan)
        points = (*_ptr_rec)->to_polygon()->points;
      result.indexs.push_back(select.id);
      for (int i = 0; i < points.size(); i++)
        result.key_points.push_back(points[i]);
    }
    auto _ptr_line = cell_reg.try_get<qlib::Path::s_ptr>(select.entity);
    if (_ptr_line) {
      result.indexs.push_back(select.id);
      result.key_points = (*_ptr_line)->spine.points;
    }
  } else if (select.type == select::SelectPartType::Edge || select.type == select::SelectPartType::BoxEdge) {
    auto _ptr_poly = cell_reg.try_get<qlib::Polygon::s_ptr>(select.entity);
    auto _ptr_elli = cell_reg.try_get<qlib::Ellipse::s_ptr>(select.entity);
    auto _ptr_rec = cell_reg.try_get<qlib::Rectangle::s_ptr>(select.entity);
    auto _ptr_fan = cell_reg.try_get<qlib::Fan::s_ptr>(select.entity);
    if (_ptr_poly || _ptr_elli || _ptr_rec || _ptr_fan) {
      qlib::Vec2dArray points;
      if (_ptr_poly)
        points = (*_ptr_poly)->points;
      if (_ptr_elli) {
        // points = (*_ptr_elli)->to_polygon()->points;
        qlib::Vec2dArray box = (*_ptr_elli)->bounding_box();
        points = qlib::box_to_points(box);
        result.is_ellipse = true;
      }

      if (_ptr_rec)
        points = (*_ptr_rec)->to_polygon()->points;
      if (_ptr_fan)
        points = (*_ptr_fan)->to_polygon()->points;
      result.indexs.push_back(select.id);
      if ((select.id + 1) == points.size()) {
        result.indexs.push_back(0);
      } else {
        result.indexs.push_back(select.id + 1);
      }

      for (int i = 0; i < points.size(); i++)
        result.key_points.push_back(points[i]);
    }

    auto _ptr_line = cell_reg.try_get<qlib::Path::s_ptr>(select.entity);
    if (_ptr_line) {
      result.indexs.push_back(select.id);
      result.indexs.push_back(select.id + 1);
      result.key_points = (*_ptr_line)->spine.points;
    }
  } else if (select.type == select::SelectPartType::Arc || select.type == select::SelectPartType::RadiusStart ||
             select.type == select::SelectPartType::RadiusEnd) {
    auto _ptr_fan = cell_reg.try_get<qlib::Fan::s_ptr>(select.entity);
    qlib::Vec2dArray points;
    if (_ptr_fan) {
      points = (*_ptr_fan)->to_polygon()->points;
      result.key_points = points;
      if (select.type == select::SelectPartType::Arc) {
        for (size_t i = 1; i < points.size() - 2; i++) {
          result.indexs.push_back(i);
          result.indexs.push_back(i + 1);
        }
      }
      if (select.type == select::SelectPartType::RadiusStart) {
        result.indexs.push_back(0);
        result.indexs.push_back(1);
      }
      if (select.type == select::SelectPartType::RadiusEnd) {
        result.indexs.push_back(points.size() - 1);
        result.indexs.push_back(0);
      }
    }
  }
  return result;
}

//部分选择对象
std::vector<PartCheckedInfo> getPartSelectedObjs(entt::registry& reg, select::SelectPartModel& select_part_model,
                                                 qbe::select::SelectCmd::PartMap& select_parts) {
  std::vector<PartCheckedInfo> part_selected_objs;
  for (const auto& [entity, data] : select_parts) {
    partSelectInfo2(reg, entity, data, part_selected_objs);
  }
  return part_selected_objs;
}

std::vector<PartCheckedInfo> getPrePartSelectedObjs(entt::registry& reg, select::SelectPartModel& select_part_model) {
  std::vector<PartCheckedInfo> pre_part_selected_objs;
  auto& select = select_part_model.hover;
  auto hover_line_ptr = reg.try_get<qlib::Path::s_ptr>(select.entity);
  auto hover_poly_ptr = reg.try_get<qlib::Polygon::s_ptr>(select.entity);
  auto hover_rect_ptr = reg.try_get<qlib::Rectangle::s_ptr>(select.entity);
  auto hover_ellipse_ptr = reg.try_get<qlib::Ellipse::s_ptr>(select.entity);
  auto hover_fan_ptr = reg.try_get<qlib::Fan::s_ptr>(select.entity);
  if (hover_line_ptr || hover_poly_ptr || hover_rect_ptr || hover_ellipse_ptr || hover_fan_ptr) {
    PartCheckedInfo sel = partSelectInfo(reg, select);
    if (sel.indexs.size() > 0)
      pre_part_selected_objs.push_back(sel);
  }
  return pre_part_selected_objs;
}

select::SelectPartModel getClippingPartSelectModel(axis::Axis& axis, std::shared_ptr<qlib::Cell> cell, layout::LayoutCmd& layout_cmd) {
  select::SelectPartModel model;
  auto& hover = model.hover;
  auto& x = axis.real_x;
  auto& y = axis.real_y;

  auto r = 5.0 / axis.scale;
  auto nodes = layout_cmd.query_quad(x, y, r);
  double dist = 9999999;
  for (auto& n : nodes) {
    auto ref_ptr = cell->reg.try_get<qlib::Reference::s_ptr>(n.entity);
    if (ref_ptr)
      continue;
    auto _ptr_line = cell->reg.try_get<qlib::Path::s_ptr>(n.entity);
    auto _ptr_poly = cell->reg.try_get<qlib::Polygon::s_ptr>(n.entity);
    auto _ptr_elli = cell->reg.try_get<qlib::Ellipse::s_ptr>(n.entity);
    auto _ptr_rec = cell->reg.try_get<qlib::Rectangle::s_ptr>(n.entity);
    auto _ptr_fan = cell->reg.try_get<qlib::Fan::s_ptr>(n.entity);
    qlib::Vec2dArray points;
    if (_ptr_line || _ptr_poly || _ptr_elli || _ptr_rec || _ptr_fan) {
      if (_ptr_line)
        points = (*_ptr_line)->spine.points;
      if (_ptr_poly)
        points = (*_ptr_poly)->points;
      if (_ptr_elli)
        points = (*_ptr_elli)->to_polygon()->points;
      if (_ptr_rec)
        points = (*_ptr_rec)->to_polygon()->points;
      if (_ptr_fan)
        points = (*_ptr_fan)->to_polygon()->points;

      auto part_nodes = layout_cmd.query_parts(n.entity, x, y, r);
      for (auto& part_n : part_nodes) {
        if (select::SelectPartType(part_n.type) == select::SelectPartType::Edge) {
          std::vector<int> edge_indexes;
          edge_indexes.push_back(part_n.id);
          if ((part_n.id + 1) == points.size()) {
            edge_indexes.push_back(0);
          } else {
            edge_indexes.push_back(part_n.id + 1);
          }
          double d = distancePointToSegment(qlib::Vec2d(x, y), points[edge_indexes[0]], points[edge_indexes[1]]);  //寻找最近距离的边
          if (d < dist) {
            dist = d;
            hover.entity = n.entity;
            hover.id = part_n.id;
            hover.type = select::SelectPartType::Edge;
            hover.edge = part_n.edge;
          }

        } else if (_ptr_fan) {
          if (part_n.type == select::SelectPartType::Arc || part_n.type == select::SelectPartType::RadiusStart ||
              part_n.type == select::SelectPartType::RadiusEnd) {
            double d = 99999;
            if (part_n.type == select::SelectPartType::RadiusStart)
              d = distancePointToSegment(qlib::Vec2d(x, y), points[0], points[1]);  //寻找最近距离的边
            if (part_n.type == select::SelectPartType::RadiusEnd)
              d = distancePointToSegment(qlib::Vec2d(x, y), points[points.size() - 1], points[0]);  //寻找最近距离的边
            if (part_n.type == select::SelectPartType::RadiusEnd) {
              for (size_t i = 1; i < points.size() - 2; i++) {
                double d_sub = distancePointToSegment(qlib::Vec2d(x, y), points[i], points[i + 1]);  //寻找最近距离的边
                d = d_sub < d ? d_sub : d;
              }
            }

            if (d < dist) {
              hover.entity = n.entity;
              hover.id = part_n.id;
              hover.type = part_n.type;  //select::SelectPartType::Edge;
              hover.edge = part_n.edge;
            }
          }
        }
      }
    }
  }
  return model;
}

void init(entt::registry& reg, ecs::Commands commands, ecs::Query query) {
  auto& state = query.get_resource<state::State>();
  state.addExitCall(state::EditingModeType::Clipping, exit_callback);
}

//修剪
void update(entt::registry& ecs_reg, ecs::Query query, ecs::Bus& bus) {
  auto& state = query.get_resource<state::State>();
  // 仅在模式执行
  if (state.getEditingMode() != state::EditingModeType::Clipping)
    return;

  auto& cmd = query.get_resource<layout::CellCmd>();
  auto cell = cmd.get_cell();
  auto& reg = cell->reg;
  auto& cell_state = query.get_resource<layout::CellState>();
  auto& axis_t = query.get_resource<axis::Axis>();
  auto& param = query.get_resource<ClippingModel>();
  auto& ex_param = query.get_resource<Extension::ExtensionModel>();
  auto& hand = query.get_resource<vsg::ref_ptr<input::HandleBundle>>();
  auto& event_writer = query.get_event_writer<Clipping::Event>();
  auto& select_event_writer = query.get_event_writer<select::Event>();
  auto& levelparam = query.get_resource<LayerRef::LayerModel>();
  auto& pick_line_points = param.pick_line_points;
  auto& select_events = query.get_event_reader<select::Event>();
  auto& undoRedoModule = query.get_resource<undoRedoT::UndoRedoModule>();
  auto& layout_cmd = query.get_resource<layout::LayoutCmd>();
  auto& select_cmd = query.get_resource<select::SelectCmd>();

  select::SelectModel& selectModel = query.get_resource<select::SelectModel>();
  select::OverallModel& overallSelect = query.get_resource<select::OverallModel>();
  select::SelectPartModel& partSelect = query.get_resource<select::SelectPartModel>();
  //清除预选择
  select_cmd.clear_hover();
  select_cmd.clear_hover_parts();
  auto& part_selects = select_cmd.select_parts();
  //禁用部分选中点
  bool update_part_render = false;
  for (auto& [entity, data] : part_selects) {
    if (!data.edge_id_map.empty()) {
      data.edge_id_map.clear();
      update_part_render = true;
    }
  }
  if (update_part_render) {
    select_cmd.remove_select_parts(part_selects);  //触发更新
  }
  //取消无法作为修剪目标对象的选中状态
  bool need_update_render = false;
  for (auto [e] : reg.view<select::SelectTag>().each()) {
    auto select_line = reg.try_get<qlib::Path::s_ptr>(e);
    auto select_polygon = reg.try_get<qlib::Polygon::s_ptr>(e);
    auto select_rectangle = reg.try_get<qlib::Rectangle::s_ptr>(e);
    auto select_ellipse = reg.try_get<qlib::Ellipse::s_ptr>(e);
    auto select_fan = reg.try_get<qlib::Fan::s_ptr>(e);
    auto select_kp = reg.try_get<qlib::KeyPoint::s_ptr>(e);
    bool valid_line = select_line && (*select_line)->getLineWidth() == 0;
    if (!valid_line && !select_polygon && !select_rectangle && !select_fan && !select_ellipse && !select_kp) {
      reg.remove<select::SelectTag>(e);
      need_update_render = true;
    }
  }
  if (need_update_render)
    select_event_writer.send(select::Event{select::Code::SelectUpdate});
  //过滤部分选中点
  bool exist_clear = false;
  partSelect.clear_selected_points(exist_clear);
  if (exist_clear)
    select_event_writer.send(select::Event{select::Code::PartSelectUpdate});

  select::SelectPartModel& partSelectModel = getClippingPartSelectModel(axis_t, cell, layout_cmd);  //query.get_resource<select::SelectPartModel>();

  std::vector<double> screen_box = axis_t.getScreenBox();
  // entt::entity& entity_hover = selectModel.entity_hover;  //预选中对象
  // auto selecc_arr = selectModel.getSelectObj();           //选中对象
  // auto hover_line_ptr = reg.try_get<qlib::Path::s_ptr>(entity_hover);
  // bool hover_a_clipping_entity = hover_line_ptr != nullptr;  //修剪对象

  if (!param.inited) {
    updateClippingStatusBarInfo(bus, false, false, false);
    param.inited = true;
  }

  //交互逻辑
  bool begin = false;
  bool update = false;
  bool cancel = false;
  bool quit = false;
  bool complete = false;
  bool to_extend = false;

  if (ex_param.key_space_switch_mode) {
    ex_param.key_space_switch_mode = false;  //从延伸切换过来的第一帧不执行
    return;
  }

  if (hand->keyReleased(vsg::KEY_Escape)) {
    quit = true;
    cancel = true;  // 按下esc时，退出
  }
  if (hand->keyReleased(vsg::KEY_Space)) {
    to_extend = true;  // 切换延伸
  } else if (hand->mousePressed(vsg::ButtonMask::BUTTON_MASK_3)) {
    cancel = true;
  } else if (hand->mousePressed(vsg::ButtonMask::BUTTON_MASK_1)) {
    if (!pick_line_points.empty() || param.can_clipping)
      complete = true;
    else
      begin = true;
  } else if (hand->mouse_move) {
    update = true;  //hand->mouse_move
  }

  //创建多选线
  if (begin) {
    if (pick_line_points.empty()) {
      layout::Vec2d pos = {axis_t.real_x, axis_t.real_y};
      pick_line_points.emplace_back(pos);
      pick_line_points.emplace_back(pos);
    } else {
      layout::Vec2d pos = {axis_t.real_x, axis_t.real_y};
      pick_line_points.back() = pos;
      pick_line_points.emplace_back(pos);
    }
  }

  qlib::Vec2d mouse_pos{axis_t.real_x, axis_t.real_y};
  ClippingData global(layout_cmd);
  global.mouse_pos = mouse_pos;
  global.levelparam = levelparam;
  global.current_cell = cell;
  global.axis_scale = axis_t.scale;
  std::vector<qlib::Vec2d> display_inters;              //所有要显示的交点
  std::vector<std::vector<qlib::Vec2d>> display_lines;  //所有要显示要截断的线
  std::vector<PartCheckedInfo> pre_hits_part = getPrePartSelectedObjs(reg, partSelectModel);
  auto clippingLineOp = [&](qlib::Path::s_ptr mouse_line, bool execute) -> void {
    bool picked_lines = false;
    bool exist_clipping_lines = false;
    if (execute) {
      global.need_overa_all_checked_datas.clear();
      global.need_part_checked_datas.clear();
    }
    std::vector<ClippingNode> clipping_nodes = getPreClippingNodes(global);
    if (clipping_nodes.empty()) {
      updateClippingStatusBarInfo(bus, picked_lines, exist_clipping_lines);
      param.can_clipping = false;
      return;
    }
    if (execute) {
      undoRedoModule.start(global.current_cell);
    }
    global.removes.clear();
    param.can_clipping = true;
    picked_lines = true;

    //**选中的靠齐对象先排除不能选中的对象如标签,如果排除完后为0个可靠齐对象则按周围对象判定**//
    bool data_changed = false;  // 判定数据是否修改

    //收集可裁切相交的选中对象
    std::vector<entt::entity> overall_selected_nodes;          //整体选中的对象
    std::vector<PartCheckedInfo> part_selected_nodes;          //部分选中的对象
    std::vector<entt::entity> nodes_o = getSelectedObjs(reg);  //LayoutCtrlData::getSelected_1()
    auto& part_selects = select_cmd.select_parts();
    std::vector<PartCheckedInfo> nodes_p = getPartSelectedObjs(reg, partSelect, part_selects);  //LayoutCtrlData::getSelected_2()
    for (auto obj : nodes_o) {
      // if (isValidClippingNode(cell, obj)) {
      overall_selected_nodes.push_back(obj);
      // }
    }
    for (auto& obj : nodes_p) {
      if (obj.indexs.size() >= 2) {
        part_selected_nodes.push_back(obj);
      }
    }
    global.overall_selected_nodes = overall_selected_nodes;
    global.part_selected_nodes = part_selected_nodes;
    for (auto& clipping_node : clipping_nodes) {
      auto path_node = reg.try_get<qlib::Path::s_ptr>(clipping_node.node);  //选中的线
      if (path_node) {
        //判断隐藏 锁定 有宽度的线
        // if (!elementIsVisible(target_path->m_elements[0].m_layer) || path_node->m_is_lock ||
        //     target_path->m_elements[0].m_half_width_and_offset.x != 0)
        //   continue;
        doClippingLine(global, clipping_node, *path_node, clipping_node.indexes, clipping_node.hit_points, display_inters, display_lines,
                       data_changed, execute, undoRedoModule);
      } else {
        auto polygon = Extension::getPolygon(global.current_cell, clipping_node.node);
        if (polygon) {
          //判断多边形隐藏 锁定
          // if (!elementIsVisible(polygon->layer) || clipping_node.node->m_is_lock) {
          //   continue;
          // }
          doClippingPolygon(global, clipping_node, polygon, clipping_node.indexes, clipping_node.hit_points, display_inters, display_lines,
                            data_changed, execute, undoRedoModule);
        }
      }
    }

    // updateDisplayInters(display_inters);
    // updateDisplayLines(display_lines);
    // }
    if (execute && data_changed) {
      // LayoutCtrlData::drawEndUndoRedo();
      // LayoutCtrlData::updateView();
      // for (auto entity : global.need_overa_all_checked_datas) {
      //   global.current_cell->reg.emplace_or_replace<select::SelectTag>(entity, select::SelectTag{});  //整体选中
      // }
      select_cmd.add_selects(global.need_overa_all_checked_datas);  //整体选中
      select::SelectCmd::PartMap parts;
      for (auto info : global.need_part_checked_datas) {
        auto add_path = global.current_cell->reg.try_get<qlib::Path::s_ptr>(info.node);
        if (add_path) {
          global.current_cell->reg.emplace_or_replace<select::SelectPartTag>(info.node, select::SelectPartTag{});
          auto& points = (*add_path)->spine.points;

          select::SelectPartData part_data;
          if (parts.count(info.node) > 0) {
            parts[info.node].edge_id_map[info.indexs[0]] = true;
          } else {
            parts[info.node] = part_data;
            parts[info.node].points = points;
            parts[info.node].edge_id_map = {{info.indexs[0], true}};
          }

          // select::SelectPartModel::Data part_data;
          // part_data.entity = info.node;
          // part_data.id = info.indexs[0];
          // part_data.type = select::SelectPartType::Edge;
          // part_data.edge = qlib::Vec2dArray{points.at(info.indexs[0]), points.at(info.indexs[1])};
          // part_data.edge_mesh = render::LineMesh(part_data.edge);
          // part_data.point_mesh = render::PointMesh(part_data.edge);
          // partSelect.selects.push_back(part_data);
        }
      }
      select_cmd.add_select_parts(parts);  //部分选中

      //删除的对象
      select_cmd.remove_selects(global.removes);       //移除选中
      select_cmd.remove_select_parts(global.removes);  //移除部分选中
      undoRedoModule.end();
      select_event_writer.send({{select::Code::SelectUpdate}});
      select_event_writer.send(select::Event{select::Code::PartSelectUpdate});
    }
    exist_clipping_lines = !display_lines.empty();
    updateClippingStatusBarInfo(bus, picked_lines, exist_clipping_lines);
  };

  if (update) {
    qlib::Path::s_ptr mouse_line = qlib::Path::create();
    if (!pick_line_points.empty()) {
      pick_line_points.back() = layout::Vec2d{axis_t.real_x, axis_t.real_y};
      mouse_line->spine.points = pick_line_points;
    }
    global.mouse_line = mouse_line;
    getPreClippingData(global, pre_hits_part);
    clippingLineOp(mouse_line, false);
  }

  if (cancel) {
    //清除可视化数据
    param.clear();
    updateClippingStatusBarInfo(bus, false, false, true);
  }

  if (quit) {
    exit(query);
    return;
  }

  if (complete) {
    //确认执行延伸
    qlib::Path::s_ptr mouse_line = qlib::Path::create();
    if (!pick_line_points.empty()) {
      mouse_line->spine.points = pick_line_points;
    }
    global.mouse_line = mouse_line;
    getPreClippingData(global, pre_hits_part);
    clippingLineOp(mouse_line, true);
    updateClippingStatusBarInfo(bus, false, false);
    pick_line_points.clear();
    display_lines.clear();
    param.clear();
  }

  // std::vector<qlib::Vec2d> ex_line1;
  // std::vector<qlib::Vec2d> ex_line2;
  // ex_line1.push_back(qlib::Vec2d(0, 20));
  // ex_line1.push_back(qlib::Vec2d(30, 30));
  // ex_line2.push_back(qlib::Vec2d(0, 30));
  // ex_line2.push_back(qlib::Vec2d(40, 40));
  // display_lines.push_back(ex_line1);
  // display_lines.push_back(ex_line2);

  if (to_extend) {
    pick_line_points.clear();
    display_lines.clear();
    exit(query);
    state.switchMode(state::EditingModeType::Extension);
    param.key_space_switch_mode = true;
    return;
  }

  if (begin || cancel || update || complete || to_extend) {
    param.updateVisualData(pick_line_points, display_lines);  //更新可视化数据
    updateVisualRender(event_writer);                         //更新可视化
  }
}

void post(entt::registry& reg, ecs::Commands commands, ecs::Query query, ecs::Bus& bus) {}

void clear_event(ecs::Query query) {
  query.get_resource<ecs::Event<Event>>().clear();
}

void ClippingPlugin::build(ecs::App& app) {
  app.init_resource<ClippingModel>(ClippingModel{});
  app.init_event<Event>();
  app.add_systems<ecs::stage::Startup>(init);
  app.add_systems<ecs::stage::Update>(update);
  app.add_systems<ecs::stage::PostUpdate>(post);
  app.add_systems<ecs::stage::Last>(clear_event);
};
}  // namespace qbe::editing::Clipping